<?php
namespace frontend\controllers;

use bc\controller\FrontController;
use bc\wx\Weixin;
use bc\mongo\WeixinUser;
use bc\mongo\WeixinAccessToken;
use bc\mongo\WeixinReplyLog;
use bc\util\Util;
use bc\util\AppConst;
use bc\wx\Auth;

/**
 * 微信测试
 */
class WeixinController extends FrontController
{
	public function actionOperate() {
		$weixin = new Weixin();
		echo $weixin->getAppId();
	}
	
	/**
	 * 微信公众号入口
	 */
	public function actionPortal()
	{
		$auth = new Auth($this->wechat()->sappid, $this->wechat()->secret);
		$accessToken = $auth->accessToken;
		$token = 'e1d18f42365847c1';
		$rs = $this->checkSignature ($token);
		
		if($rs === true)
			echo $_GET['echostr'];
// 		$weixin = new Weixin();
// 		//签名验证逻辑
// // 		if($weixin->checkSignature()){
// // 			echo $_GET['echostr'];
// // 		}
// // 		exit;
// 		//读取原始请求数据
// 		$msg = $weixin->getRawMsg();
		
// 		//推送日志
// 		$pushlog = new WeixinPushLog();
// 		$pushlog->logWeixinPush($msg);
		
// 		$msgObj = $weixin->parseMsg($msg);
// 		if ($msgObj === false || !is_object($msgObj)) {
// 			exit;
// 		}
// 		switch ($msgObj->MsgType) {
// 			case 'event' : //接收事件消息
// 				$this->handleEventMsg($msgObj);
// 				break;
// 			default :
// 				//todo
// 				break;
// 		}
	}
	
	/**
	 * 处理事件推送消息
	 * @param $msgObj 接收到的消息体
	 */
	private function handleEventMsg($msgObj)
	{
		//$this->load->model('scenemodel', 'scModel');
		$weixin = new Weixin();
		$openId = $msgObj->FromUserName;
		$fromUserName = $msgObj->ToUserName;
		//未关注，关注后推送
		if ($msgObj->Event == 'subscribe') {
			if (isset($msgObj->EventKey) && preg_match('/qrscene_(.*)/', $msgObj->EventKey, $scene)) {
				switch ($scene[1]) {
					case AppConst::SCENE_ALCOHOL://酒精检测扫码关注
						$pushData['Title'] = '酒精检测——大声告诉你，你的酒量在哪？';
						$pushData['PicUrl'] = 'http://mmbiz.qpic.cn/mmbiz/JZZx5GGu9S7ULUkp44x6t9ib6FqVSfkb1H11knpPI4V4QQje49bsozQGta7OkHddOYW4VyZPjwJNVU0YaiaGJ2Eg/640?wx_fmt=png&wxfrom=5&wx_lazy=1';
						$pushData['Description'] = '玩武松打虎，看酒量何处！？你是否知道自己的量在哪？我们告诉你，你能喝一缸！';
						$pushData['Url'] = 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=207709834&idx=1&sn=6ac76ca4d7839c10453e572c461b77c4#rd';
						break;
					case AppConst::SCENE_DEAF://耳聋检测扫码关注
						$pushData['Title'] = '为了那句我爱你 拒绝药物性耳聋';
						$pushData['PicUrl'] = 'http://mmbiz.qpic.cn/mmbiz/JZZx5GGu9S5Y5nnFarWgYqo4VWsa3lOwubtavpFYhlA6BF8llQQ5ghIX6Unibv1A0AuxyAOeJvyM3aHQvkKcibfw/0?wx_fmt=jpeg';
						$pushData['Description'] ='药物性耳聋是指因使用某些药物或接触某些化学制剂而引起的耳聋。而能导致药物性耳聋的药物则称为耳毒性药物。';
						$pushData['Url'] = 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=208088108&idx=1&sn=820c4cf8f7125f63ed183e02f69313a2&scene=0&from=singlemessage&isappinstalled=0#rd';
						break;
				}
				
				$msg = $weixin->createRawTuWenMsg($fromUserName, $openId, array($pushData));
				$replyLogMongo = new WeixinReplyLog();
				$replyLogMongo->logWeixinReply($msg, 'tuwen');
			} else {
				//普通关注，接收场景值id
				$pushData['PicUrl'] = 'http://mmbiz.qpic.cn/mmbiz/JZZx5GGu9S6YEcAaQqGiatuX3rzDfweCw3xrbQDX5OA6Buk2gYYSJw6Q5JWnPnvBH1jIoQjLE0Nngfwt9CiauJyQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1';
				$pushData['Title'] = '基因检测，带你一起探索生命的奥妙 ';
				$pushData['Description'] = '为什么不同人在身高、体重、肤色和形状上长得不一样？但是往往又和自己的父母相似？';
 				$pushData['Url'] = 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=207684459&idx=1&sn=957e0137b70e3eb06c2c830fe8ee98b3#rd';
// 				$pushData['Url'] = 'http://www.baidu.com';
				$msg = $weixin->createRawTuWenMsg($fromUserName, $openId, array($pushData));
				$replyLogMongo = new WeixinReplyLog();
				$replyLogMongo->logWeixinReply($msg, 'tuwen');
			}
	
			//一旦用户关注产生关注行为，则更新用户资料
			//$this->load->model('wxusermodel', 'weixinUserModel');
			$weixin = new WeixinUser();
			$weixin->updateUserByOpenid($openId);
			die($msg);
		} elseif ($msgObj->Event == 'SCAN') {
			
			
// 			$scene_id = $msgObj->EventKey;
// 			$pushData = $this->scModel->getSceneById($scene_id, $openId);
// 			$msg = $this->wx->createTuWenMsg($fromUserName, $openId, array($pushData));
// 			$this->wxModel->logWeixinReply($msg, 'tuwen');
// 			die($msg);
		} elseif($msgObj->Event == 'CLICK'){
// 			$key = $msgObj->EventKey;
// 			$pushData = $this->scModel->getSpeMenuClick($key);
// 			$msg = $this->wx->createRawTuWenMsg($fromUserName, $openId, $pushData);
// 			$this->wxModel->logWeixinReply($msg, 'tuwen');
// 			die($msg);
		}
	}
	
// 	public function actionAccess() {
// 		$tokenMongo = new WeixinAccessToken();
// 		$access_token = $tokenMongo->getAccessToken();
// 		echo $access_token;
// 	}
	
	/**
	 * 获取用户信息
	 * @author pwstrick
	 */
	public function actionUser() {
		/*
		 * 编写授权页面
		 */
		//echo $weixin->createAuthUrl('http://wsdev.baiaimama.com/weixin/user');

		$user = $this->getWeixinUser();
// 		if(!empty($user)) {
// 			$weixinUser = new WeixinUser();
// 			$exists = $weixinUser->getUserByOpenId($user['openid']);
// 			if(empty($exists))
// 				$weixinUser->add($user);
// 		}
		print_r($this->user());
		print_r($this->openid());
		print_r($this->uid());
	}
	
	/**
	 * 创建自定义菜单
	 * token = md5('menu'+inner_weixin_key+'menu')
	 * eg. 795bd9d95a5f840f6cfe819a0c66d1d0
	 *
	 * @param $token
	 */
	public function actionCreatemenu()
	{
		$token = $this->get('token');
		$innerWeixinKey = WEIXIN_INNER_KEY;
		$trueToken = md5('menu' . $innerWeixinKey . 'menu');
		if ($token != $trueToken) {
			$this->innerOutput(1, '无法通过请求认证');
		}
		$weixin = new Weixin();
		//echo $weixin->createAuthUrl(Util::baseUrl('alcohol/orderinput?pid=1'));exit;
		//请注意菜单中的中文一定要采用某种方编码
		$menu = array(
			'button' => array(
					array(
						'name' => $this->encodeZH('基因介绍'),
						'sub_button' => array(
							array(
								'type' => 'view',
								'name' => $this->encodeZH('基因检测'),
								'key' => 'MENU_GENE_INDEX',
								//'url' => $weixin->createAuthUrl(Util::baseUrl('alcohol/orderinput'))
								'url' => 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=207684459&idx=1&sn=957e0137b70e3eb06c2c830fe8ee98b3#rd'
							),
							array(
								'type' => 'view',
								'name' => $this->encodeZH('趣味文章'),
								'key' => 'MENU_ARTICLE',
								'url' => 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=207684503&idx=1&sn=dda2664ed8b1a5dcc5fd440f0a796056#rd'
							),
							array(
								'type' => 'view',
								'name' => $this->encodeZH('产品预告'),
								'key' => 'MENU_PRODUCT',
								'url' => 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=207684412&idx=1&sn=86b921fafda6a85637224cc49112eaee#rd'
							)
						)
					),
					array(
						'name' => $this->encodeZH('产品流程'),
						'sub_button' => array(
							array(
								'type' => 'view',
								'name' => $this->encodeZH('药物致聋'),
								'key' => 'MENU_DEAF_INDEX',
								//'url' => $weixin->createAuthUrl(Util::baseUrl('alcohol/orderinput'))
								'url' => 'http://ws.baiaimama.com/deaf/index'
							),
							array(
								'type' => 'view',
								'name' => $this->encodeZH('武松打虎'),
								'key' => 'MENU_GAME',
								'url' => $weixin->createAuthUrl(Util::baseUrl('alcohol/gamealcohl'))
							),
							array(
								'type' => 'view',
								'name' => $this->encodeZH('酒精检测'),
								'key' => 'MENU_PRODUCT_DETAIL',
								'url' => 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=207709834&idx=1&sn=6ac76ca4d7839c10453e572c461b77c4&scene=0#rd'
							),
							array(
								'type' => 'view',
								'name' => $this->encodeZH('耳聋检测'),
								'key' => 'MENU_DEAF_DETAIL',
								'url' => 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=208088108&idx=1&sn=820c4cf8f7125f63ed183e02f69313a2&scene=0&from=singlemessage&isappinstalled=0#rd'
							),
							array(
								'type' => 'view',
								'name' => $this->encodeZH('查看报告'),
								'key' => 'MENU_READ',
								'url' => $weixin->createAuthUrl(Util::baseUrl('alcohol/report'))
							)
						)
					),
					array(
						'name' => $this->encodeZH('公司信息'),
						'sub_button' => array(
							array(
								'type' => 'view',
								'name' => $this->encodeZH('公司简介'),
								'key' => 'MENU_COMPANY',
								'url' => 'http://mp.weixin.qq.com/s?__biz=MzI1NjAxODE2MQ==&mid=207709782&idx=1&sn=8facd6f02fa1ff707b076e57856404a4#rd'
							),
// 							array(
// 								'type' => 'view',
// 								'name' => $this->encodeZH('联系我们'),
// 								'key' => 'MENU_CONTACH',
// 								'url' => 'http://a.app.qq.com/o/simple.jsp?pkgname=com.baiaimama.android'
// 							)
						)
					)
				)
		);
	
		$menuMsg = $this->decodeZHMsg(json_encode($menu));
		
		$accessMongo = new WeixinAccessToken();
		$access_token = $accessMongo->getAccessToken();
		if (!$access_token) {
			$this->innerOutput(2, '无法获取access_token');
		}
		$weixin = new Weixin();
		$res = $weixin->customMenu($menuMsg, $access_token);
		if (!$res) {
			$this->innerOutput(3, '菜单创建失败');
		}
		$this->innerOutput(0, '菜单创建成功');
	}
	
	/**
	 * 针对中文字符串编码
	 * @param $name
	 * @return string
	 */
	private function encodeZH($name)
	{
		return '[@' . base64_encode($name) . '@]';
	}
	
	/**
	 * 内部服务器请求时输出
	 *
	 * @param int $code 返回状态码
	 * @param string $msg 返回消息
	 * @param array $data 返回数据
	 */
	private function innerOutput($code, $msg = '', $data = array())
	{
		echo json_encode(array('code' => $code, 'msg' => $msg, 'data' => $data));
		exit;
	}
	
	/**
	 * 针对消息中存在中文编码过的串进行解码
	 * @param $msg
	 * @return mixed
	 */
	private function decodeZHMsg($msg)
	{
		return preg_replace_callback('/\[\@(.+?)\@\]/', function ($match) {
			return base64_decode($match[1]);
		}, $msg);
	}
	
	/**
	 * 获取二维码原始信息
	 * token = md5(id+inner_weixin_key+id)
	 * token 60df752ccce46f4fac0d74e0eac5a180
	 *
	 * @param $scene 1酒精 2耳聋
	 * @param $token
	 */
	public function actionGetqrcode()
	{
		$params = $this->getParams();
		//解析字符串
		$scene = $params['scene'];
		$token = $params['token'];
	
		$innerWeixinKey = WEIXIN_INNER_KEY;
		$trueToken = md5($scene . $innerWeixinKey . $scene);
		if ($token != $trueToken) {
			$this->innerOutput(1, '无法通过请求认证');
		}
		$accessMongo = new WeixinAccessToken();
		$access_token = $accessMongo->getAccessToken();
		if (!$access_token) {
			$this->innerOutput(2, '无法获取access_token');
		}
		
		$weixin = new Weixin();
		$qrdata = $weixin->getQrticket($access_token, $scene);
		
		if (!$qrdata || !is_array($qrdata)) {
			$this->innerOutput(3, '无法获取二维码信息');
		}
		$this->innerOutput(0, '成功获取二维码信息', $qrdata);
	}
	
	
	private function checkSignature($token)
	{
	        $signature = $_GET ["signature"];
	        $timestamp = $_GET ["timestamp"];
	        $nonce = $_GET ["nonce"];
	
	
	        $tmpArr = array (
                        $token,
                        $timestamp,
                        $nonce
	        );
	        sort ( $tmpArr, SORT_STRING );
	        $tmpStr = implode ( $tmpArr );
	        $tmpStr = sha1 ( $tmpStr );
	
	        if ($tmpStr == $signature)
	        {
	                return true;
	        }
	        else
	        {
	                return false;
	        }
	}
}